package com.jw.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @Author jiangwang
 * @Created by 2021/9/26 18:47
 * @Description: TODO
 */
@Configuration
public class ShiroConfig
{
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager)
    {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        HashMap<String, String> filterMap = new LinkedHashMap<>();

        //授权
        filterMap.put("/userInfo/userAdd", "perms[userInfo:add]");
        filterMap.put("/userInfo/userDel", "perms[userInfo:del]");
        filterMap.put("/userInfo/userList", "perms[userInfo:view]");

        //需要拦截的url
        filterMap.put("/userInfo/*", "authc");
        //不需要拦截的页面
        filterMap.put("/static/**", "anon");
        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
//        filterMap.put("/logOut", "logout");
        //被拦截的页面跳转到登录页面
        bean.setLoginUrl("/toLogin");
        //登录成功后跳转的链接
        bean.setSuccessUrl("/index");

        bean.setUnauthorizedUrl("/noAuthorization");
        bean.setFilterChainDefinitionMap(filterMap);
        return bean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager()
    {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(myRealm());
        return defaultWebSecurityManager;
    }

    @Bean
    public MyRealm myRealm()
    {
        return new MyRealm();
    }

    @Bean
    public ShiroDialect getShiroDialect()
    {
        return new ShiroDialect();
    }
}
